package com.twang.stock.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.twang.stock.Entity.ShiShiData;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.design.impl.OneThsHotStockListTask;
import com.twang.stock.design.impl.ThsHotStockListTask;
import com.twang.stock.design.impl.TodayQinXuTask;
import com.twang.stock.dto.BaseRequest;
import com.twang.stock.dto.WanZhuHotUserDto;
import com.twang.stock.entity.DfcfBanKuaiMaoLiLv;
import com.twang.stock.entity.User;
import com.twang.stock.entity.WanZhuHotStock;
import com.twang.stock.entity.ex.CompanyStockMinutesEx;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.*;
import com.twang.stock.service.impl.CompanyStockServiceImpl;
import com.twang.stock.service.impl.IndexServiceImpl;
import com.twang.stock.task.QueryBanKuaiAndDaPan;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping(value = "/")
@Slf4j
public class IndexController {

    @Autowired
    private CompanyStockService companyStockService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BaseTask baseTask;

    @Autowired
    private IndexService indexService;


    @Resource
    private ZhangTingBanTaskService zhangTingBanTaskService;

    @Autowired
    private UserService userService;

    @Autowired
    private TodayQinXuTask todayQinXuTask;
    @Autowired
    private WenCaiDataService wenCaiDataService;

    @Autowired
    private MinutesChengJIaoeService minutesChengJIaoeService;

    @Autowired
    private IndexRiskService indexRiskService;

    @Autowired
    private WanZhuBeiChiChangService wanZhuBeiChiChangService;


    @RequestMapping(value = "/")
    public ModelAndView bigData(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        OneThsHotStockListTask.dataSize=5;
        ThsHotStockListTask.dataSize=50;
        indexService.indexDataInitNew(modelAndView);
        indexService.获取市场高度(modelAndView);
        indexService.获取市场涨停成交额(modelAndView);
        List<WanZhuHotStock> wanZhuHotStocks= wanZhuBeiChiChangService.查询当日热榜(HolidayCopy.getToday());
        List<WanZhuHotUserDto> wanZhuHotUserDtos=wanZhuBeiChiChangService.查看热门选手(HolidayCopy.getToday());
        modelAndView.addObject("wanZhuHotUserDtos", wanZhuHotUserDtos);
        modelAndView.addObject("wanZhuHotStocks", wanZhuHotStocks);
        modelAndView.addObject("wanZhuHotStocksDate", wanZhuHotStocks.get(0).getDate());
        modelAndView.setViewName("index/index0415");
        return modelAndView;
    }

    @RequestMapping(value = "/risk")
    public ModelAndView risk(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        indexRiskService.indexDataInit(modelAndView);
        modelAndView.setViewName("index/index_v3");
        return modelAndView;
    }



    @RequestMapping(value = "/gaodu")
    public ModelAndView gaodu(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        indexService.获取市场高度(modelAndView);
        modelAndView.setViewName("index/gaodu");
        return modelAndView;
    }

    @RequestMapping(value = "/gnqd")
    public ModelAndView 概念强度(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("duanxian/lian_ban");
        return modelAndView;
    }

    /**
     * 连扳成交额
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/lbcje")
    public ModelAndView lbcje(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        indexService.获取市场高度(modelAndView);
        indexService.获取市场涨停成交额(modelAndView);
        modelAndView.setViewName("index/lianBanChenJiaoE");
        return modelAndView;
    }

    /**
     * 连扳成交额
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/todayVolumeExceedingBillion")
    public ModelAndView todayVolumeExceedingBillion(String date) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<CompanyStockMinutesEx> todayVolumeExceedingBillion = minutesChengJIaoeService.getTodayVolumeExceedingBillion(date);
        modelAndView.addObject("todayVolumeExceedingBillion", todayVolumeExceedingBillion);
        modelAndView.setViewName("billionTradeStock");
        return modelAndView;
    }



    @RequestMapping(value = "mobile")
    public ModelAndView mobile() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        OneThsHotStockListTask.dataSize=5;
        ThsHotStockListTask.dataSize=5;
        indexService.indexDataInitNew(modelAndView);
        modelAndView.setViewName("index/mobile");
        return modelAndView;
    }

    @RequestMapping(value = "minutesAmount")
    public ModelAndView minutesAmount(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        todayQinXuTask.execute(modelAndView,null);
        modelAndView.setViewName("index/ui_liang_neng");
        return modelAndView;
    }

    @RequestMapping(value = "/ndzfb")
    public ModelAndView ndzfb(BaseRequest request) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<DfcfBanKuaiMaoLiLv> maoLiLvs =wenCaiDataService.获取年度涨幅前20();
        modelAndView.addObject("nianDuZhangFu", maoLiLvs);
        modelAndView.setViewName("index/wenCaiData");
        return modelAndView;
    }

    @GetMapping(value = "/banKuaiMaoLiLv")
    public ModelAndView banKuaiMaoLiLv(String banKuai) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        String key="ban_kuai_mao_li_lv_"+banKuai+"_"+HolidayCopy.getRealToday();
        Object obj = redisUtil.get(key);
        if (null == obj) {
            List<DfcfBanKuaiMaoLiLv> maoLiLvs= QueryBanKuaiAndDaPan.获取板块咱得排行个股(banKuai);
            //只看公司印象
            zhangTingBanTaskService.initKanDian(maoLiLvs, Boolean.FALSE);
            if (!CollectionUtils.isEmpty(maoLiLvs)) {
                String str = JSONObject.toJSONString(maoLiLvs);
                redisUtil.set(key, str);



















































                obj=str;
            }
        }
        modelAndView.addObject("maoLiLvs",JSONObject.parseArray(obj.toString(), DfcfBanKuaiMaoLiLv.class));
        modelAndView.setViewName("bankuai_mao_li_lv_table_tag");
        return modelAndView;
    }


    @GetMapping(value = "/chengJiaoE")
    public ModelAndView chengJiaoE(String banKuai) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        Object obj = redisUtil.get(IndexServiceImpl.STOCK_TRADE_SUM);
        //查询数据
        if (null == obj) {
            zhangTingBanTaskService.chengJiaoECache();
            Boolean falg = Boolean.TRUE;
            while (falg) {
                obj = redisUtil.get(IndexServiceImpl.STOCK_TRADE_SUM);
                if (null != obj) {
                    falg = Boolean.FALSE;
                }
            }
        }
        List<DfcfBanKuaiMaoLiLv> maoLiLvs = JSONObject.parseArray(obj.toString(), DfcfBanKuaiMaoLiLv.class);
        modelAndView.addObject("todayChengJiao", maoLiLvs);
        modelAndView.setViewName("cheng_Jiao_e_100");
        return modelAndView;
    }

    @GetMapping(value = "/stockKanDian")
    public ModelAndView stockKanDian(String code) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        String result = indexService.getOneStockInfo(code.replace("sh","").replace("sz",""));
        modelAndView.addObject("maoLiLvs", JSONObject.parseArray(result, DfcfBanKuaiMaoLiLv.class));
        modelAndView.setViewName("bankuai_mao_li_lv_table_tag");
        return modelAndView;
    }



    /**
     * 新增预警股票
     *
     * @param code
     * @param desc
     * @throws Exception
     */
    @RequestMapping(value = "/addStock")
    public void addStock(String code, String desc, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String msg="";
        if(null==userService.getUserByToken()){
            throw new Exception("请登录,默认邮箱账号+密码：123456");
        }else{
            User user = userService.getUserByToken();
            redisUtil.del(new StringBuffer(CompanyStockServiceImpl.ZI_XUAN_CHI_KEY).append("_").append(user.getId()).toString());
            companyStockService.addStock(code, desc,user.getId(),null);
            msg="添加成功！";
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        //输出到客户端
        out.println(msg);
        out.flush();
        out.close();
    }

    /**
     * 删除预警股票
     *
     * @param id
     * @throws Exception
     */
    @RequestMapping(value = "/delStock")
    public void delStock(Integer id, HttpServletResponse response) throws Exception {
        companyStockService.delStock(id);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        //输出到客户端
        out.println("删除成功！");
        out.flush();
        out.close();
    }

    /**
     * 置顶
     *
     * @param id
     * @throws Exception
     */
    @RequestMapping(value = "/zhiDingStock")
    public void zhiDingStock(Integer id, HttpServletResponse response) throws Exception {
        companyStockService.zhiDingStock(id);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        //输出到客户端
        out.println("设置成功！");
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/ajaxRequest")
    public void ajaxRequestGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
                doAjaxRequestGetSyn(request,response);
    }

    @RequestMapping(value = "/ajaxRequestEbay")
    public void ajaxRequestEbay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        ShiShiData shiShiData=new ShiShiData();
        shiShiData.setCode(code);
        shiShiData.setGpname("请输入产品类型");
        //输出到客户端
        out.println(JSONObject.toJSONString(shiShiData));
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/ajaxRequestGetList")
    public void ajaxRequestGetList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        doAjaxRequestGetSynList(request,response);
    }

    /**
     * 异步请求-单个
     * @param request
     * @param response
     * @throws IOException
     */
    private void doAjaxRequestGetSyn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        ShiShiData shiShiData;
        if (!baseTask.isWorkTradeTime()) {
            Object object = redisUtil.get(code);
            if (null != object) {
                //取缓存数据
                shiShiData = (ShiShiData) object;
            } else {
                //获取表单控件值
                shiShiData = HtmlTools.getGpdatas(Lists.newArrayList(code)).get(0);
                shiShiData.setZhangdie(shiShiData.getZhangdie().setScale(2, BigDecimal.ROUND_HALF_UP));
                redisUtil.set(shiShiData.getCode(), shiShiData);
            }
        } else {
            //获取表单控件值
            shiShiData = HtmlTools.getGpdatas(Lists.newArrayList(code)).get(0);
            shiShiData.setZhangdie(shiShiData.getZhangdie().setScale(2, BigDecimal.ROUND_HALF_UP));
            redisUtil.set(shiShiData.getCode(), shiShiData);
        }
        //输出到客户端
        out.println(JSONObject.toJSONString(shiShiData));
        out.flush();
        out.close();
    }
    /**
     * 异步请求-list
     * @param request
     * @param response
     * @throws IOException
     */
    private void doAjaxRequestGetSynList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String code = request.getParameter("code");
        //获取表单控件值
        List<String> param=Lists.newArrayList();
        if(code.contains(",")){
            param= Arrays.asList(code.split(","));
        }else{
            param= Lists.newArrayList(code);
        }
        //
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        List<ShiShiData> shiShiDataList=Lists.newArrayList();
        param.stream().forEach(item-> {
            try {
                ShiShiData shiShiData;
                if (!baseTask.isWorkTradeTime()) {
                    Object object = redisUtil.get(code);
                    if (null != object) {
                        //取缓存数据
                        shiShiData = (ShiShiData) object;
                    } else {
                        shiShiData = HtmlTools.getGpdatas(Lists.newArrayList(item)).get(0);
                        shiShiData.setZhangdie(shiShiData.getZhangdie().setScale(2, BigDecimal.ROUND_HALF_UP));
                        redisUtil.set(shiShiData.getCode(), shiShiData);
                    }
                } else {
                    //获取表单控件值
                    shiShiData = HtmlTools.getGpdatas(Lists.newArrayList(item)).get(0);
                    shiShiData.setZhangdie(shiShiData.getZhangdie().setScale(2, BigDecimal.ROUND_HALF_UP));
                    redisUtil.set(shiShiData.getCode(), shiShiData);
                }
                shiShiDataList.add(shiShiData);
            }catch (Exception e){
                log.info(e.getMessage());
            }
        });
        //输出到客户端
        out.println(JSONObject.toJSONString(shiShiDataList));
        out.flush();
        out.close();
    }
    @RequestMapping(value = "/indexNew")
    public ModelAndView indexNew(BaseRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/index_v5");
        return modelAndView;
    }

}
